//
//  NetAccess.m
//  PropertyButler
//
//  Created by 2015Lab-MC on 16/3/1.
//
//

#import "NetAccess.h"
#import "AFNetworking.h"
#import "AppDelegate.h"

@interface NetAccess ()

@property (nonatomic, strong) AFURLSessionManager *sessionManager;

@property (nonatomic, strong) NSURLSessionDataTask *dataTask;

@end

@implementation NetAccess

+ (instancetype) sharedNetAccess {
    return [[NetAccess alloc] init];
}


- (instancetype)init
{
    self = [super init];
    if (self) {
        
        self.sessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:nil];
        //     self.sessionManager.securityPolicy = [self sslSecurityPolicy];
        
    }
    return self;
}



- (void) postDownLoadDataWithUrl:(NSString *)url andWithParameters:(id)parameter withSuccessBlock:(void(^)(NSDictionary *json))success failedBlock:(void(^)(NSError *error)) failed {
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:parameter error:nil];
    //    [request setValue:@"text/html;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
    request.timeoutInterval = 20.0f;
    
    
    self.dataTask = [self.sessionManager dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
        
    } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
        
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            failed(error);
        }else {
            if ([responseObject integerForKey:@"code"] == 101) {
                //token失效，重新登录
                [kAppDelegate changeRootViewController:NO];
            }else{
                success((NSDictionary *)responseObject);
            }
        }
        
        //        NSLog(@"NSURLResponse = %@ res = %@, error= %@",response,responseObject,error);
        //        NSLog(@"URL = %@?%@",url,[[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding]);
        
    }];
    [self.dataTask resume];
}



- (void)cancel
{
    [self.dataTask cancel];
}

@end
